using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ButtonInteractive : MonoBehaviour
{
	public Text title;
	public Text[] infos;
	public ButtonMultiple btnDrop;
	public ButtonMultiple btnAction;
	public Text btnActionText;

	private bool hasButtons;
	private int nbInfos;
	private Player player;
	private InteractiveInfo objInfo;

	private static bool m_CanClick = true;

	private void Awake()
	{
		Character.characterModified += CharacterModified;
	}

	private void OnDestroy()
	{
		Character.characterModified -= CharacterModified;
	}

	private void CharacterModified()
	{
		if (objInfo)
		{
			btnDrop.Disable(!player.CanDropItem());
		}
	}

	public void Setup(Player _owner, InteractiveInfo _info, bool _hasButtons, bool _fromEquipped)
	{
		player = _owner;
		objInfo = _info;
		title.text = _info.itemName;
		string[] strings = _info.GetStrings();
		nbInfos = strings.Length;
		for (int i = 0; i < infos.Length; i++)
		{
			if (i < strings.Length)
			{
				infos[i].text = strings[i];
			}

			infos[i].gameObject.SetActive(false);
		}

		btnAction.gameObject.SetActive(false);
		btnDrop.Disable(!player.CanDropItem());
		btnDrop.gameObject.SetActive(false);

		if (_info is UseableInfo)
		{
			UseableInfo useable = _info as UseableInfo;
			if (useable.actionButton == UseableInfo.ActionButton.Equip && _fromEquipped)
			{
				btnActionText.text = "Unequip";
			}
			else
			{
				btnActionText.text = useable.actionButton.ToString();
			}
		}

		hasButtons = _hasButtons && objInfo is UseableInfo;
	}

	public void OnClick()
	{
		for (int i = 0; i < nbInfos; i++)
		{
			infos[i].gameObject.SetActive(!infos[i].gameObject.activeSelf);
		}

		if (InitiativeManager.Instance.current is Player)
		{
			if (hasButtons)
			{
				btnAction.gameObject.SetActive(!btnAction.gameObject.activeSelf);
			}

			btnDrop.gameObject.SetActive(!btnDrop.gameObject.activeSelf);
		}
	}

	public void OnClick_Action(bool i_Equip)
	{
		if (m_CanClick)
		{
			UseableInfo useable = objInfo as UseableInfo;
			switch (useable.actionButton)
			{
			case UseableInfo.ActionButton.Equip:
				(InitiativeManager.Instance.current as Player).SwitchEquipped(useable);
				break;
				
			case UseableInfo.ActionButton.Apply:
			case UseableInfo.ActionButton.Drink:
			case UseableInfo.ActionButton.Use:
				break;
			}
			
			m_CanClick = false;
			Invoke("CanClickAgain", 0.5f);
		}
	}

	public void OnClick_Drop()
	{
		if (m_CanClick)
		{
			(InitiativeManager.Instance.current as Player).DropItem(objInfo);
			
			m_CanClick = false;
			Invoke("CanClickAgain", 0.5f);
		}
	}

	// There is a problem with the object on which this script is on, it's buttons are clicked twice in a single frame
	private void CanClickAgain()
	{
		m_CanClick = true;
	}
}
